package com.wuyou.controller;

import com.alibaba.fastjson.JSON;
import com.wuyou.service.ItemPageService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;


@Controller
@RequestMapping("/itemPage")
@RocketMQMessageListener(topic = "auditHouse", consumerGroup = "wuyouhome")
public class ItemPageController implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Resource
    private ItemPageService itemPageService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void onMessage(String message) {

    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
                MessageExt messageExt = list.get(0);
                int reconsumeTimes = messageExt.getReconsumeTimes();//重试次数
                try {
                    String msgId = messageExt.getMsgId();
                    //判断当前redis库中有没有当前的消息ID
                    if (!redisTemplate.hasKey("WUYOUHOME_HOUSE_" + msgId)) {
                        byte[] body = messageExt.getBody();
                        String msg = new String(body);
                        List<Long> ids = JSON.parseArray(msg, Long.class);
                        for (Long id : ids) {
                            itemPageService.createPage(id);
                        }
                        redisTemplate.opsForValue().set("WUYOUHOME_HOUSE_" + msgId, "已经消费");
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;//消费成功返回CONSUME_SUCCESS
                } catch (Exception e) {
                    e.printStackTrace();
                    //重试次数小于2进行重试
                    if (reconsumeTimes < 2) {
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                    //放入死信队列
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            }
        });
    }
}
